package mysql

import (
	"furni-suite/furnirpc/furnirpc"
	"gorm.io/gorm"
)

type Furniture struct {
	gorm.Model
	FurnName string `gorm:"type:varchar(30);not null;comment:家具名称"`
	BrandId  int64  `gorm:"type:int(11);not null;comment:品牌id"`
	ClassId  int64  `gorm:"type:int(11);not null;comment:分类id"`
}

func (f *Furniture) Furniture(db *gorm.DB) error {
	return db.Debug().Create(f).Error
}

func (f *Furniture) FindFurnitureByName(db *gorm.DB, name string) error {
	return db.Debug().Where("furn_name=?", name).First(f).Error
}

func FurnitureShow(db *gorm.DB, id int64) *furnirpc.FurnitureShowResponse {
	var data *furnirpc.FurnitureShowResponse
	db.Debug().Model(&Furniture{}).
		Select(
			"furnitures.id AS furniture_id",
			"furnitures.furn_name AS furn_name",
			"classes.`name` AS class_name",
			"brands.`name` AS brand_name",
		).
		Joins("LEFT JOIN brands ON furnitures.brand_id = brands.id").
		Joins("LEFT JOIN classes ON furnitures.class_id = classes.id").
		Where("furnitures.id = ?", id).
		First(&data)
	return data

}
func FurnitureList(db *gorm.DB, in *furnirpc.FurnitureListShowRequest) []*furnirpc.FurnitureList {
	/*
		SELECT
		  furnitures.id AS furniture_id,
		  furnitures.furn_name AS furn_name,
		  classes.`name` AS class_name,
		  brands.`name` AS brand_name
		FROM
		  furnitures
		  LEFT JOIN brands ON furnitures.brand_id = brands.id
		  LEFT JOIN classes ON furnitures.class_id = classes.id
	*/
	var data []*furnirpc.FurnitureList
	db.Debug().Model(&Furniture{}).
		Select(
			"furnitures.id AS furniture_id",
			"furnitures.furn_name AS furn_name",
			"classes.`name` AS class_name",
			"brands.`name` AS brand_name",
		).
		Joins("LEFT JOIN brands ON furnitures.brand_id = brands.id").
		Joins("LEFT JOIN classes ON furnitures.class_id = classes.id").
		Scopes(Paginate(int(in.Page), int(in.Size))).Find(&data)
	return data
}
